package com.ludomancy.gamelib.entity;

import java.awt.Rectangle;

import com.ludomancy.gamelib.WorldScreenProjection;

public class EntityCollisionFilter implements EntityFilter
{
	private Entity center;
	private WorldScreenProjection proj;

	public EntityCollisionFilter(Entity center)
	{
		this(center, null);
	}
	
	public EntityCollisionFilter(Entity center, WorldScreenProjection proj)
	{
		this.center = center;
		this.proj = proj;
	}
	
	private static int[] getBitmask(Entity from, int x, int y, int w, int h, WorldScreenProjection proj)
	{
		int screenX = proj.worldToScreenX(x);
		int screenY = proj.worldToScreenY(y);
		int screenW = proj.worldToScreenX(w);
		int screenH = proj.worldToScreenY(h);
		return from.getBitmask(screenX, screenY, screenW, screenH);
	}
	
	public static boolean collidesWith(Entity e1, Entity e2, WorldScreenProjection proj)
	{
		if(e1 != e2)
		{
			Rectangle r1 = new Rectangle(e1.pos.x - e1.getWidth()/2, e1.pos.y - e1.getHeight()/2, e1.getWidth(), e1.getHeight());
			Rectangle r2 = new Rectangle(e2.pos.x - e2.getWidth()/2, e2.pos.y - e2.getHeight()/2, e2.getWidth(), e2.getHeight());
			if(r1.intersects(r2))
			{
				Rectangle inter = r1.intersection(r2);
				if(proj != null)
				{
					if(proj.worldToScreenX(inter.width) == 0 || proj.worldToScreenY(inter.height) == 0)
					{
						return false;
					}

					int[] p1 = getBitmask(e1, inter.x-r1.x, inter.y-r1.y, inter.width, inter.height, proj);
					if(p1 != null)
					{
						int[] p2 = getBitmask(e2, inter.x-r2.x, inter.y-r2.y, inter.width, inter.height, proj);
						if(p2 != null)
						{
							for (int i = 0; i < p1.length; i++)
							{
								int alpha1 = (p1[i] >> 24) & 0xFF;
								int alpha2 = (p2[i] >> 24) & 0xFF;
								if(alpha1 > 0 && alpha2 > 0)
								{
									return true;
								}
							}
							return false;
						}
					}
				}
				return true;
			}
		}
		return false;
	}
	
	public boolean accepts(Entity e)
	{
		return collidesWith(e, center, proj);
	}
}